package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type IIndexImgRepository interface {
	Find(db *gorm.DB, pair *queryWrapper.WherePair) ([]*model.IndexImg, error)
	DeleteBatch(db *gorm.DB, ids []uint) error
	Create(db *gorm.DB, indexImg *model.IndexImg) error
	FindPage(db *gorm.DB, params *pagehelper.Params) ([]*model.IndexImg, error)
	Count(db *gorm.DB, params *pagehelper.Params) (int64, error)
	FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (indexImg *model.IndexImg, err error)
	FindById(db *gorm.DB, imgId uint) (*model.IndexImg, error)
	Updates(db *gorm.DB, id uint, columns map[string]interface{}) error
}

type IndexImgRepository struct{}

func NewIndexImgRepository() IIndexImgRepository {
	return &IndexImgRepository{}
}

func (r *IndexImgRepository) Find(db *gorm.DB, pair *queryWrapper.WherePair) (list []*model.IndexImg, err error) {
	return list, queryWrapper.ReuseWherePair(db.Model(&model.IndexImg{}), pair).Find(&list).Error
}

func (r *IndexImgRepository) DeleteBatch(db *gorm.DB, ids []uint) error {
	return db.Delete(&model.IndexImg{}, ids).Error
}

func (r *IndexImgRepository) Create(db *gorm.DB, indexImg *model.IndexImg) error {
	return db.Model(&model.IndexImg{}).Create(&indexImg).Error
}

func (r *IndexImgRepository) FindPage(db *gorm.DB, params *pagehelper.Params) (list []*model.IndexImg, err error) {
	tx := queryWrapper.ReuseWherePair(db.Model(&model.IndexImg{}), params.WherePair)
	return list, tx.Scopes(pagehelper.Paginate(params.Current, params.Size)).Find(&list).Error
}

func (r *IndexImgRepository) Count(db *gorm.DB, params *pagehelper.Params) (count int64, err error) {
	tx := queryWrapper.ReuseSelect(db.Model(&model.IndexImg{}), params.SelectFields)
	return count, queryWrapper.ReuseWherePair(tx, params.WherePair).Count(&count).Error
}

func (r *IndexImgRepository) FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (indexImg *model.IndexImg, err error) {
	tx := queryWrapper.ReuseWherePair(db.Model(&model.IndexImg{}), pair)
	return indexImg, tx.First(&indexImg).Error
}

func (r *IndexImgRepository) FindById(db *gorm.DB, imgId uint) (indexImg *model.IndexImg, err error) {
	return indexImg, db.First(&indexImg, imgId).Error
}

func (r *IndexImgRepository) Updates(db *gorm.DB, id uint, columns map[string]interface{}) error {
	return db.Model(&model.IndexImg{}).Where("img_id = ?", id).Updates(columns).Error
}
